<template>
	<nut-overlay
		v-model:visible="isShow"
		:close-on-click-overlay="false"
		:overlay-style="{
			backgroundColor: 'rgba(0, 0, 0, .5)',
		}"
	>
		<div class="login_pop" v-if="isShow">
			<div class="login">
				<p class="title_p">
					<span>{{ state.formData?.title ? t(state.formData?.title) : '' }}</span>
					<iconpark-icon class="close" icon-id="exit" color="#fff" size="1.3rem" @click="closeDialog"></iconpark-icon>
				</p>
				<div class="content">
					<div class="tab" v-if="state.formData?.tabList">
						<span
							:class="state.formData.active == tab.value ? 'active_tab' : ''"
							v-for="(tab, i) in state.formData.tabList"
							:key="i"
							@click="changeTab(tab.value, tab)"
							>{{ t(tab.name) }}</span
						>
					</div>

					<nut-form ref="formRef" label-position="top" :model-value="state.formData?.formParams" :show-label="state.formData?.showLabel">
						<template v-for="(item, i) in state.formData?.list">
							<div style="font-size: 14px; margin-bottom: 8px; color: #fff; line-height: 21px; width: 307px" v-if="item.subtitle && item.show">
								{{ item.subtitle }}
							</div>
							<nut-form-item :label="t(item.label)" v-if="item.show" :prop="item.name" :rules="state.formData?.rules[item.name]" :key="i">
								<nut-input
									clearable
									:type="item.type"
									v-model="state.formData.formParams[item.name]"
									:disabled="item.disabled"
									@blur="blurValidate(item.name)"
									@update:model-value="changeValidate(item.name)"
									:placeholder="t(item.placeholder)"
								>
									<template #left v-if="item.leftIcon && item.isMobile">
										<span v-if="item.isMobile" style="color: #fff; margin-right: 10px; line-height: 14px"
											>+{{ state.formData.formParams.codeValue }}</span
										>
									</template>
									<template #right v-if="item.changeRightIcon">
										<span @click="iconClick(item)" v-if="item.changeRightIcon" style="color: #8e82c2 !important; font-size: 18px !important">
											<iconpark-icon v-if="item.type == 'password'" name="hide" color="#8e82c2" size="1rem"></iconpark-icon>
											<iconpark-icon v-if="item.type == 'text'" name="eye12" color="#8e82c2" size="1rem"></iconpark-icon>
										</span>
									</template>
								</nut-input>
								<span @click="submitSend(item)" v-if="item.name == 'captcha'" class="btn">
									<ImgT :src="state.captchaURL" :key="state.captchaURL" v-if="state.captchaURL" alt="" />
									<iconpark-icon icon-id="signicon08" color="#fff" size="1.5rem"></iconpark-icon>
								</span>
								<nut-button
									:bordered="false"
									:loading="item.loading"
									@click="submitSend(item)"
									v-if="item.slot && item.type == 'code'"
									class="btn btn_inline"
									:disabled="item.btnDisabled"
									>{{ isNaN(item.timeText) ? t(item.timeText) : item.timeText }}</nut-button
								>
							</nut-form-item>
						</template>
					</nut-form>

					<div style="margin-top: 16px">
						<nut-button :loading="props.loading" class="btn_block" round block @click="submitNext">
							{{ state.formData?.buttonText && t(state.formData?.buttonText) }}
						</nut-button>
					</div>
				</div>
			</div>
		</div>
	</nut-overlay>

	<Modal v-model:visible="SMSModal" :title="t('home_page_smsTitle')">
		<div class="tips">
			<p>
				{{ t('home_page_smsContent') }}<b>{{ t('home_page_smsPrice') }}</b
				>{{ t('home_page_smsContent1') }}
			</p>
			<p style="margin-top: 24px">
				{{ t('home_page_smsContent2') }}
				<span @click="changeTab(state.formData?.tabList[2].value, state.formData?.tabList[2])">{{ t('contactService') }}</span>
			</p>
			<nut-button style="margin-top: 24px" class="btn_block" :bordered="false" block @click="sendMobileSmsCode">
				{{ t('btn_label_submit') }}</nut-button
			>
		</div>
	</Modal>
</template>

<script setup lang="ts">
import PKwebsocket from '@/lolo/Ws';
import { NetPacket } from '@/netBase/NetPacket';
import { ref, reactive } from 'vue';
import { showNotify } from '@nutui/nutui';
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const props: any = defineProps({
	loading: {
		type: Boolean,
		deafult: false,
	},
});

const SMSModal = ref(false);
const emit = defineEmits(['changeTab', 'submitData', 'nextChange', 'onClose']);
const formRef = ref();
const isShow = ref(true);
const state: any = reactive({
	itemClick: null,
	formData: null,
	type: 0,
	codeOptions: [
		{
			label: '84',
			value: '84',
		},
	],
});

const iconClick = (a: any) => {
	if (a.type == 'password') {
		a.type = 'text';
	} else {
		a.type = 'password';
	}
};
const blurValidate = (name: string) => {
	formRef.value?.validate(name).then();
};
const changeValidate = (name: string) => {
	if (['mobile', 'email', 'new_password_confirm'].includes(name)) {
		formRef.value?.validate(name).then();
	}
};
const changeTab = (tabId: number, item: any) => {
	if (!item.isLink) {
		resetInputHide();
	}
	state.formData.formParams = state.formInitValue;
	emit('changeTab', tabId, state.formData);
};
const resetInputHide = () => {
	for (const key in state.formData.list) {
		state.formData.list[key].show = false;
	}
};

const submitNext = () => {
	// 效验
	if (state.type == 3) {
		formRef.value?.validate().then(({ valid, errors }: any) => {
			if (valid) {
				if (state.formData.active == 1 && state.formData.phoneStep == 1) {
					emit('nextChange', state.formData.formParams);
				} else if (state.formData.active == 2 && state.formData.emailStep == 1) {
					emit('nextChange', state.formData.formParams);
				} else {
					emit('submitData', state.formData.formParams, state.type);
				}
			} else {
				console.log(errors);
			}
		});
	} else {
		//常规修改密码
		formRef.value?.validate().then(({ valid, errors }: any) => {
			if (valid) {
				emit('submitData', state.formData.formParams, state.type);
			} else {
				console.log(errors);
			}
		});
	}
};

// 手机验证码协议
const sendMobileSmsCode = () => {
	state.itemClick.loading = true;
	SMSModal.value = false;
	if (state.formData.forgetPassword) {
		const req = NetPacket.req_get_mobile_sms_login_code();
		req.mobile = state.formData.formParams.codeValue + state.formData.formParams.mobile;
		PKwebsocket.instance.send(req, false, {
			callbackName: 'msg_nodify_get_mobile_sms_login_code',
			callback: handleSMSback,
		});
	} else {
		const req = NetPacket.req_get_mobile_sms_code();
		req.mobile = state.formData.formParams.codeValue + state.formData.formParams.mobile;
		if (state.formData.list.mobile.disabled) {
			req.operate_type = 3;
		} else {
			req.operate_type = 1;
		}
		PKwebsocket.instance.send(req, false, {
			callbackName: 'msg_notify_get_mobile_sms_code',
			callback: handleSMSback,
		});
	}
};

// 发送验证码
const submitSend = (item: any) => {
	state.itemClick = item;
	// 1 为手机  2 为邮箱
	if (state.formData.active == 1) {
		formRef.value?.validate('mobile').then(({ valid, errors }: any) => {
			if (valid) {
				SMSModal.value = true;
			} else {
				console.warn('error:', errors);
			}
		});
	}
	if (state.formData.active == 2) {
		formRef.value?.validate('email').then(({ valid, errors }: any) => {
			if (valid) {
				item.loading = true;
				const req = NetPacket.req_get_email_verification_code();
				req.email = state.formData.formParams.email;
				req.operate_type = 5;
				PKwebsocket.instance.send(req, false, {
					callbackName: 'msg_notify_get_email_verification_code',
					callback: handleEmailback,
				});
			} else {
				console.warn('error:', errors);
			}
		});
	}
};

// 邮箱验证码发送结果
const handleEmailback = (res: any) => {
	state.formData.list.emailCode.loading = false;
	if (res.code == 1) {
		if (res.message) {
			showNotify.success(t(res.message));
		}
		state.formData.list.emailCode.btnDisabled = true;
		state.formData.list.emailCode.timeText = 180;
		setTimeout(() => {
			state.formData.list.emailCode.loading = false;
		}, 300);
		state.formData.list.emailCode.timer = setInterval(() => {
			state.formData.list.emailCode.timeText--;
			if (state.formData.list.emailCode.timeText <= 0) {
				clearInterval(state.formData.list.emailCode.timer);
				state.formData.list.emailCode.btnDisabled = false;
				state.formData.list.emailCode.timer = null;
				state.formData.list.emailCode.timeText = 'get_verification_code';
			}
		}, 1000);
	} else {
		console.log(6666666, res);
	}
};
// 返回修改密码手机验证码是否发送
const handleSMSback = (res: any) => {
	state.formData.list.phoneCode.loading = false;
	if (res.code == 1) {
		if (res.message) {
			showNotify.success(t(res.message));
		}
		state.formData.list.phoneCode.btnDisabled = true;
		state.formData.list.phoneCode.timeText = 180;
		setTimeout(() => {
			state.formData.list.phoneCode.loading = false;
		}, 300);
		state.formData.list.phoneCode.timer = setInterval(() => {
			state.formData.list.phoneCode.timeText--;
			if (state.formData.list.phoneCode.timeText <= 0) {
				clearInterval(state.formData.list.phoneCode.timer);
				state.formData.list.phoneCode.btnDisabled = false;
				state.formData.list.phoneCode.timer = null;
				state.formData.list.phoneCode.timeText = 'get_verification_code';
			}
		}, 1000);
	}
};

// 关闭弹窗
const closeDialog = () => {
	isShow.value = false;
	if (state.formData.list?.emailCode) {
		clearInterval(state.formData.list?.emailCode?.timer);
		state.formData.list.emailCode.disabled = true;
		state.formData.list.emailCode.timer = null;
		state.formData.list.emailCode.timeText = 'get_verification_code';
	}
	if (state.formData.list?.phoneCode?.timer) {
		clearInterval(state.formData.list.phoneCode.timer);
		state.formData.list.phoneCode.disabled = true;
		state.formData.list.phoneCode.timer = null;
		state.formData.list.phoneCode.timeText = 'get_verification_code';
	}
	console.log(state.formData?.formParams);
	emit('onClose');
	state.formData.formParams = state.formInitValue;
};
// 打开弹窗
const openDialog = async (formData: any, type: number) => {
	state.formData = formData; //JSON.parse(JSON.stringify(formData)) //
	state.formInitValue = JSON.parse(JSON.stringify(formData.formParams));
	state.type = type;
	isShow.value = true;
};

defineExpose({
	openDialog,
	closeDialog,
});
</script>
<style lang="scss" scoped>
.login_pop {
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.login {
	border-radius: 16px;
	background: #131232;
	box-shadow: 0.5px 0.5px 1px 0px #2e296b inset;
	width: 347px;

	:deep(.nut-input-value) {
		border-radius: 8px;
		background: #1d1c3c;
		box-shadow: 0.5px 0.5px 1px 0px #333260 inset;
		height: 44px;
		line-height: 44px;
		padding: 0 14px;
	}
	:deep(.nut-cell) {
		width: 307px;
	}

	:deep(.nut-form-item) {
		padding: 0 0 14px 0 !important;

		.nut-cell__title {
			display: none !important;
		}
	}

	:deep(.nut-cell-group__wrap) {
		box-shadow: none;
		margin: 0;
	}

	:deep(.nut-form-item__body__slots) {
		display: flex;
	}

	:deep(.nut-cell-group .nut-cell::after) {
		border: none;
	}

	:deep(.nut-form-item.error.line::before) {
		border: none;
	}

	:deep(.nut-input-right-box) {
		position: relative;
	}

	:deep(.input-text) {
		&::placeholder {
			color: #504f6f !important;
		}
	}

	.title_p {
		border-bottom: 0.5px solid #242352;
		height: 48px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #fff;
		font-size: 16px;
		font-weight: 500;
		line-height: 16px;
		position: relative;

		.close {
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
			right: 20px;
			color: #fff;
			font-size: 20px;
		}
	}

	.content {
		padding: 20px 16px 32px 16px;

		.tab {
			width: 307px;
			height: 40px;
			margin: 0 auto 20px auto;
			display: flex;
			justify-content: space-around;
			align-items: center;
			border-radius: 8px;
			background: #0b0b23;

			> span {
				width: 100px;
				height: 32px;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #504f6f;
				font-size: 14px;
				font-weight: 400;
			}

			.active_tab {
				border-radius: 8px;
				background: linear-gradient(180deg, #5567ff 0%, #9e1eff 100%);
				box-shadow: 0.5px 0.5px 1px 0px #9b9eff inset;
				color: #fff;
				font-weight: 500;
				margin: 2px;
			}
		}
	}

	.btn {
		min-width: 110px;
		height: 44px;
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		border-radius: 8px !important;
		overflow: hidden;
		// position: relative;
		// left: 12px;
		margin-left: 10px;
		background-color: #0f052a;

		> img {
			width: 100%;
			height: 100%;
		}
	}

	.btn_block {
		width: 307px;
		border-radius: 8px !important;
		background: linear-gradient(180deg, #5567ff 0%, #9e1eff 100%);
		box-shadow: 0.5px 0.5px 1px 0px #9b9eff inset;
		height: 44px;
		margin-top: 10px;
		margin-left: 3px;
	}
}

.tips {
	text-align: start;
	padding: 29px 20px 30px 20px !important;

	p {
		color: #fff;
		font-family: 'PingFang SC';
		font-size: 14px;
		font-style: normal;
		font-weight: 500;
		line-height: 21px;
		/* 150% */

		> b {
			color: #ed8302;
		}

		> span {
			color: #e43939;
			cursor: pointer;
		}
	}
}
</style>
